% setup env
clear all;
close all;
clc;

% schem parameter
R = 120;
L = 100e-6;
C = 33e-12;

% Resonance friquecy
f0 = 1 / (2*pi * sqrt(L*C));
fprintf('f0 = %f MHz\n', f0/1e6); 
%Discrete time
T = 10e-5 / f0;
Tmod = 20 / f0;

% time vector
t = 0:T:Tmod;

% Testing model
E = 0*(t<Tmod/4)+1*(t>=Tmod/4);
%plot(t,E);

% init array
U = nan(1, length(t));
dU = nan(1, length(t));
I = nan(1, length(t));

% initial condition
U(1) = 0;
dU(1) = 0;
I(1) = 0;

for k = 2:length(t)
    U(k) = U(k-1) + dU(k-1)*T;
    I(k) = I(k-1) + T*(E(k) - I(k-1)*R -U(k-1)) / L;
    dU(k) = I(k) / C;
end

% plottig
graphics_toolkit gnuplot
figure;
[y1, x1] = max(U(1:floor(end/2)));
[y2, x2] = max(U(ceil(end/2):end));
plot(t.*10e+6,E,t.*10e+6,U,'linewidth',2,[t(x1),t(x2+ceil(length(U)/2)) ] .* 10e+6, [y1,y2], '*');
text (t(x1) * 10e+6+1, y1, sprintf("x = %e\ny = %e" ,t(x1), y1))
text (t(x2+ceil(length(U)/2)) * 10e+6+1, y2, sprintf("x = %e\ny = %e" ,t(x2+ceil(length(U)/2)), y2))

fprintf("T = %e\n",t(x2+ceil(length(U)/2))-t(x1));

grid on
title('Reaction to Step function', 'FontSize',14);
xlabel('t, us', 'FontSize',14);
ylabel('U, E, V', 'FontSize',14);
%legend ({'I am blue', 'I am green'}, 'location', 'east');
legend({'E(t)', 'U(t)'}, 'location', 'northeast');
print -deps -color "./Check_the_Model.eps"
print -dpng -color "./Check_the_Model.png"
